import fs from 'fs'
import path from 'path'
import ignore from 'ignore'
import fs_promises from 'fs/promises'
import type { Options } from 'ignore'

export function readIgnoreFile(filePath: string, options: ReadIgnoreOptions = {}) {
  const { defaultPattern = [], encoding = 'utf-8', ignoreOptions } = options

  if (!fs.existsSync(filePath)) {
    throw new Error(`Ignore file not found: ${filePath}`)
  }

  const content = fs.readFileSync(filePath, encoding)

  return ignore(ignoreOptions).add(defaultPattern).add(content)
}

export function readIgnoreFileAsync(filePath: string, options: ReadIgnoreOptions = {}) {
  const { defaultPattern = [], encoding = 'utf-8', ignoreOptions } = options

  if (!fs.existsSync(filePath)) {
    throw new Error(`Ignore file not found: ${filePath}`)
  }

  return fs_promises.readFile(filePath, encoding).then((content) => {
    return ignore(ignoreOptions).add(defaultPattern).add(content)
  })
}

type ReadIgnoreOptions = {
  defaultPattern?: string[]
  /**
   * @default 'utf-8'
   */
  encoding?: BufferEncoding
  ignoreOptions?: Options
}

export const globify = (pattern: string) => pattern.split('\\').join('/')

export const relative = (filePath: string, rootPath: string) => {
  return globify(path.relative(rootPath, filePath))
}
